//
//  PywBuriedRequestService.m
//  PywSdk
//
//  Created by Ampaw on 2017/11/15.
//  Copyright © 2017年 Jade. All rights reserved.
//

#import "PywBuriedRequestService.h"
#import <objc/runtime.h>
#import "YYFTAFNetworking.h"
#import "AppUtil.h"
#import "PywBuriedDataHandler.h"

@interface PywBuriedRequestService()
@property (nonatomic, strong) YYFTAFHTTPRequestSerializer<YYFTAFURLRequestSerialization> *requestSerializer;

@end

@implementation PywBuriedRequestService

static PywBuriedRequestService *instance;
+ (PywBuriedRequestService *)sharedBuriedService
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[PywBuriedRequestService alloc] init];
    });
    return instance;
}

#pragma mark - getters and setters
- (YYFTAFHTTPRequestSerializer<YYFTAFURLRequestSerialization> *)requestSerializer{
    if (!_requestSerializer) {
        _requestSerializer = [YYFTAFHTTPRequestSerializer serializer];
        NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingISOLatin1);
        _requestSerializer.stringEncoding = enc;
        [_requestSerializer setTimeoutInterval:30];
    }
    return _requestSerializer;
}

/**
 请求 上传用户行为数据
 
 @param paramterLists 用户行为数据集
 @param success 成功回调
 @param failure 失败回调
 */
- (void)requestUserActionWithParamterLists:(NSMutableArray *)paramterLists
                                   Success:(void(^)(NSDictionary *dict))success
                                   Failure:(void(^)(NSError *error))failure
{
    // 请求地址
    NSString *requestUrl = [NSString stringWithFormat:@"%@",userActionDataUrl];
    
    // 请求参数加密
    NSData *requestData = [self getRequestDatas:paramterLists];
    if (!requestData){
        NSLog(@"没有存储数据！");
        return;
    }
    
    // 创建请求
    NSMutableURLRequest *request = [self.requestSerializer
                                    multipartFormRequestWithMethod:@"POST"
                                    URLString:requestUrl
                                    parameters:nil
                                    constructingBodyWithBlock:nil
                                    error:nil];
    [request setHTTPBody:requestData];

    // 发送任务
    YYFTAFHTTPSessionManager *sessionManager = [YYFTAFHTTPSessionManager manager];
    sessionManager.responseSerializer = [YYFTAFHTTPResponseSerializer serializer];
    [[sessionManager dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        NSDictionary *resultDict = [NSDictionary new];
        if (!error && responseObject) {
            NSError *pError = nil;
            // 解析数据
            resultDict = [NSJSONSerialization JSONObjectWithData:[AppUtil decode:responseObject]
                                                         options:NSJSONReadingMutableContainers
                                                           error:&pError];
            if (pError) {
                NSLog(@"\n---------- Response Desc = %@ ----------\n",response.description);
                NSLog(@"\n---------- Error Desc =%@ ----------\n",pError.description);
                return;
            }
            // 回调数据
            success(resultDict);
        }else{
            NSLog(@"网络请求错误提示: \n%@",error);
            // 回调数据
            failure(error);
        }
    }] resume];
}

/**
 * 1. 转json Data
 * 2. AppUtil 加密
 * 3. base64
 * 4. 转字符串
 * 5. 添加数组
 * 6. 数组转Data
 */
- (NSData *)getRequestDatas:(NSMutableArray *)monitors
{
    NSMutableArray *array = [NSMutableArray array];
    for (PywBuriedDataHandler *monitor in monitors) {
        // 1. 转jsonData
        NSData *jsonData = [self toJSONDataWithModel:monitor];
        // 2. AppUtil 加密
        NSData *encodeData = [AppUtil encode:jsonData];
        // 3. base64
        NSData *base64Data = [encodeData base64EncodedDataWithOptions:NSDataBase64Encoding64CharacterLineLength];
        // 4. 转字符串
        NSString *dataStr = [[NSString alloc] initWithData:base64Data encoding:NSUTF8StringEncoding];
        // 5. 添加数组
        [array addObject:dataStr];
    }
    if (array.count == 0) {
        return nil;
    }
    
    // 6. 数组转Data
    NSData *arrayData = [NSJSONSerialization dataWithJSONObject:array options:NSJSONWritingPrettyPrinted error:nil];
    return arrayData;
}

/// 将model转Data
- (NSData *)toJSONDataWithModel:(PywBuriedDataHandler *)model
{
    NSDictionary *dict = [self entityToDictionary:model];
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict
                                                       options:NSJSONWritingPrettyPrinted
                                                         error:nil];
    return jsonData;
}

//实体对象转为字典对象
- (NSDictionary *)entityToDictionary:(id)entity
{
    Class clazz = [entity class];
    u_int count;
    
    objc_property_t* properties = class_copyPropertyList(clazz, &count);
    NSMutableArray* propertyArray = [NSMutableArray arrayWithCapacity:count];
    NSMutableArray* valueArray = [NSMutableArray arrayWithCapacity:count];
    
    for (int i = 0; i < count ; i++)
    {
        objc_property_t prop=properties[i];
        const char* propertyName = property_getName(prop);
        
        [propertyArray addObject:[NSString stringWithCString:propertyName encoding:NSUTF8StringEncoding]];
        
        //        const char* attributeName = property_getAttributes(prop);
        //        NSLog(@"%@",[NSString stringWithUTF8String:propertyName]);
        //        NSLog(@"%@",[NSString stringWithUTF8String:attributeName]);
        
        id value =  [entity performSelector:NSSelectorFromString([NSString stringWithUTF8String:propertyName])];
        if(value ==nil)
            [valueArray addObject:[NSNull null]];
        else {
            [valueArray addObject:value];
        }
        //        NSLog(@"%@",value);
    }
    
    free(properties);
    
    NSDictionary* returnDic = [NSDictionary dictionaryWithObjects:valueArray forKeys:propertyArray];
//    NSLog(@"%@", returnDic);
    
    return returnDic;
}

@end
